﻿using Microsoft.AspNetCore.Mvc;
using Urs.Admin.Models.Payments;
using Urs.Core;
using Urs.Core.Plugins;
using Urs.Data.Domain.Configuration;
using Urs.Services.Configuration;
using Urs.Services.Payments;
using Urs.Services.Plugins;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Framework.Mvc;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class PaymentController : BaseAdminController
	{
		#region Fields

        private readonly IPaymentService _paymentService;
        private readonly PaymentSettings _paymentSettings;
        private readonly ISettingService _settingService;
        private readonly IPermissionService _permissionService;
        private readonly IPluginFinder _pluginFinder;
        private readonly IWebHelper _webHelper;

		#endregion

		#region Constructors

        public PaymentController(IPaymentService paymentService, PaymentSettings paymentSettings,
            ISettingService settingService, IPermissionService permissionService,
            IWebHelper webHelper,
            IPluginFinder pluginFinder)
		{
            this._paymentService = paymentService;
            this._paymentSettings = paymentSettings;
            this._settingService = settingService;
            this._permissionService = permissionService;
            this._pluginFinder = pluginFinder;
            this._webHelper = webHelper;
		}

		#endregion 

        #region Methods


        public IActionResult MethodUpdate(PaymentMethodModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePaymentMethods))
                return HttpUnauthorized();

            var pm = _paymentService.LoadPaymentMethodBySystemName(model.SystemName);
            if (pm.IsPaymentMethodActive(_paymentSettings))
            {
                if (!model.IsActive)
                {
                    //mark as disabled
                    _paymentSettings.ActivePaymentMethodSystemNames.Remove(pm.PluginDescriptor.SystemName);
                    _settingService.SaveSetting(_paymentSettings);
                }
            }
            else
            {
                if (model.IsActive)
                {
                    //mark as active
                    _paymentSettings.ActivePaymentMethodSystemNames.Add(pm.PluginDescriptor.SystemName);
                    _settingService.SaveSetting(_paymentSettings);
                }
            }
            var pluginDescriptor = pm.PluginDescriptor;
            pluginDescriptor.FriendlyName = model.FriendlyName;
            pluginDescriptor.DisplayOrder = model.DisplayOrder;
            PluginManager.SavePluginDescriptor(pluginDescriptor);
            //reset plugin cache
            _pluginFinder.ReloadPlugins(pluginDescriptor);

            return new NullJsonResult();
        }

        #endregion
    }
}
